package com.ligq.vbasedemo.encode

import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.util.Log
import com.ligq.common.utils.FileUtils
import com.ligq.vbasedemo.MainActivity.TAG


const val VALUE_FRAME_RATE = 30

class H264CameraEncode(private val width: Int, private val height: Int) {
    private lateinit var mediaCodec: MediaCodec
    private var index = 0
    fun startLive() {
        try {
            val format =
                MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height)
            mediaCodec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
            format.setInteger(MediaFormat.KEY_BIT_RATE, width * height)
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
            format.setInteger(MediaFormat.KEY_FRAME_RATE, VALUE_FRAME_RATE)
            format.setInteger(
                MediaFormat.KEY_COLOR_FORMAT,
                MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible
            )
            mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
            mediaCodec.start()
        } catch (e: Exception) {
            Log.e(TAG, "startLive: ", e)
        }

    }

    fun encodeFrame(data: ByteArray?) {
        val inputIndex = mediaCodec.dequeueInputBuffer(10000)
        val bufferInfo = MediaCodec.BufferInfo()
        //输入相机数据
        if (inputIndex >= 0) {
            val inputBuffer = mediaCodec.getInputBuffer(inputIndex)!!
            inputBuffer.clear()
            inputBuffer.put(data!!)
            mediaCodec.queueInputBuffer(inputIndex, 0, data.size, compPts().toLong(), 0)
            index++
        }

        //输出dsp编码数据
        val outIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 10000)
        if (outIndex >= 0) {
            val outputBuffer = mediaCodec.getOutputBuffer(outIndex)
            // bufferInfo 数据与 outputBuffer数据长度一致
            Log.d(
                TAG,
                "encodeFrame: bufferInfo size=${bufferInfo.size},outputBuffer size=${outputBuffer!!.remaining()}"
            )
            val tempData = ByteArray(bufferInfo.size)
            outputBuffer.get(tempData)
            FileUtils.writeBytes(tempData)
            FileUtils.writeContent(tempData)
            mediaCodec.releaseOutputBuffer(outIndex, false)
        }
    }

    private fun compPts() = 1000000 / VALUE_FRAME_RATE * index
}